package com.nineclock.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.PhoneNumCheckUtils;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {


    @Override
    public Boolean checkMobileExists(String mobile) {
        int count = this.count(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getMobile, mobile ));
        return count>=1;
    }


    @Autowired
    private SmsService smsService;

    @Override
    public Long register(SysRegisterDTO dto) {
        //1.检查参数合法性
        if(StrUtil.isEmpty(dto.getMobile()) || StrUtil.isEmpty(dto.getCheckcode()) || StrUtil.isEmpty(dto.getPassword())){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //2.校验手机格式是否正确
        if(!PhoneNumCheckUtils.isPhoneLegal(dto.getMobile())){
            throw new NcException(ResponseEnum.INVALID_PHONE_NUMBER);
        }

        //3.校验验证码是否正确
        String redisKey = SMSConstant.SMS_REGISTER_KEY_PREFIX + dto.getMobile();

        if(!smsService.verifySmsCode(dto.getCheckcode(),dto.getMobile(), SMSConstant.SMS_TYPE_REGISTER)){
            throw new NcException(ResponseEnum.INVALID_VERIFY_CODE);
        }

        //4.判断手机号是否被注册过
        int count = this.count(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getMobile, dto.getMobile()));
        if(count>0){
            throw new NcException(ResponseEnum.USER_MOBILE_EXISTS);
        }

        //5.保存用户信息
        SysUser sysUser = new SysUser();
        sysUser.setMobile(dto.getMobile());
        sysUser.setPassword(new BCryptPasswordEncoder().encode(dto.getPassword()));
        sysUser.setStatus((short)1);
        this.save(sysUser);

        //6.删除验证码
        smsService.deleteSmsCode(dto.getMobile(), SMSConstant.SMS_TYPE_REGISTER);


        return sysUser.getId();
    }
}
